//
//  VehicleGaoJinDetailController.m
//  Runone
//
//  Created by runone02 on 16/11/30.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "VehicleGaoJinDetailController.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "DetailModel.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "UIView+Addition.h"
#import "EnlargeMapViewController.h"
#import "OneConst.h"
#import "ROPointAnnotation.h"
#import "CustomCallOutView.h"
#import "CustomAnnotationView.h"
#import "AppDelegate.h"
#import "OneConst.h"
#import "CameraDetailController.h"
#import "HighwayMergeRoadRecordModel.h"


@interface VehicleGaoJinDetailController ()<UITableViewDelegate, UITableViewDataSource, MAMapViewDelegate>
@property (nonatomic, strong)  MAMapView *mapView; //地图
@property (nonatomic, strong)  UITableView *tableView;
@property (nonatomic, strong)  DetailModel *dataSource;

@property (nonatomic, strong) DeviceBaseInfo *baseInfoModel;

@property (nonatomic, strong) UIButton *cameraBtn;

@property (nonatomic, assign) AllIconType type;
@end

@implementation VehicleGaoJinDetailController

#pragma   ------两客一危告警信息界面数据点击
#pragma 两客一危 车辆信息


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadMapView]; //加载地图
    [self defaultAnnimation]; //设置到广乐路段
    [self judgeVehicleDeatilType];
    [self loadAnnotaion];
    [self configNavigationBar];
    [self configView];
    [self showCameraGunArround2KM];
    [self request];
    self.view.backgroundColor=[UIColor whiteColor];
//    _tableView.delegate   = self;
//    _tableView.dataSource = self;

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)judgeVehicleDeatilType {
    if ([_gaoModel.VehicleDetailType isEqualToString:@"2"]) {
        _type = AllIconTypeDangerous;//危化品车图标
    }else {
        _type = AllIconTypeBus;// 客车图标
    }
}

- (void)loadMapView {
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,250)];
    _mapView.delegate     = self;
    _mapView.showsCompass = NO;
    _mapView.showsScale   = YES;
    _mapView.scaleOrigin  = CGPointMake(0, 210);
    [_mapView setZoomLevel:8];
    [self.view addSubview:_mapView];
}

-(void)defaultAnnimation {
    MACoordinateSpan span                   = MACoordinateSpanMake(0.027149, 0.052268);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake([_gaoModel.Latitude floatValue], [_gaoModel.Longitude floatValue]);
    MACoordinateRegion region               = MACoordinateRegionMake(centerCoordinate, span);
    _mapView.region                         = region;
}

- (void) loadAnnotaion {
    NSMutableArray *pointAnnotaionArray = [[NSMutableArray alloc] init];
    ROPointAnnotation *centerAnnotaion  = [[ROPointAnnotation alloc] init];
    centerAnnotaion.coordinate = CLLocationCoordinate2DMake([_gaoModel.Latitude floatValue], [_gaoModel.Longitude floatValue]);
    [pointAnnotaionArray addObject:centerAnnotaion];
    [_mapView addAnnotation:centerAnnotaion];
}

- (void) configNavigationBar {
    
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:(68.0 / 255) green:(169.0 / 255) blue:(213.0 / 255) alpha:1.000]];
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    
    UILabel *titleLabel  = [[UILabel alloc] init];
    titleLabel.size      = CGSizeMake(100, 30);
    titleLabel.text      = _gaoModel.VehicleNo;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
}

- (void)configView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 260, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CellID"];
    _tableView.dataSource = self;
    _tableView.delegate   = self;
    _tableView.bounces    = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_tableView];
    //放大按钮
    UIButton *enlargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [enlargeBtn setBackgroundImage:[UIImage imageNamed:@"map_enlarge"] forState:UIControlStateNormal];
    [enlargeBtn addTarget:self action:@selector(enlargeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    enlargeBtn.frame  =  CGRectMake(_mapView.bounds.size.width - 35 - 10, 74, 35, 35);
    [self.view addSubview:enlargeBtn];
    //路况
    UIButton *trafficBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    [trafficBtn setBackgroundImage:[UIImage imageNamed:@"traffic_light"] forState:UIControlStateNormal];
    [trafficBtn setBackgroundImage:[UIImage imageNamed:@"traffic_light_selected"] forState:UIControlStateSelected];
    [trafficBtn addTarget:self action:@selector(trafficBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    trafficBtn.frame = CGRectMake(_mapView.bounds.size.width - 35 - 10, 114, 35, 35);
    [self.view addSubview:trafficBtn];
    //
    _cameraBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    _cameraBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _cameraBtn.frame           = CGRectMake(self.view.bounds.size.width - 120, 210, 100, 30);
    [_cameraBtn setBackgroundImage:[UIImage imageNamed:@"camera_gun_btn_bg"] forState:UIControlStateNormal];
    [_cameraBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 0)];
    [_cameraBtn addTarget:self action:@selector(cameraGunClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cameraBtn];
}

- (void)enlargeBtnClick:(UIButton *)btn {
    EnlargeMapViewController *vc = [[EnlargeMapViewController alloc] init];
    vc.la = [_gaoModel.Latitude floatValue];
    vc.lo = [_gaoModel.Longitude floatValue];
    vc.type = _type;
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)trafficBtnClick:(UIButton *)btn {
    NSLog(@"trafficeBtn");
    btn.selected = !btn.selected;
    if (btn.selected) {
        _mapView.showTraffic = YES;
    } else {
        _mapView.showTraffic = NO;
    }
}

- (void)request {
    RequestHelper *requestHelper = [[RequestHelper alloc] init];
    RequestGinsengModel *GetAllLastestVehicleDynamicModel = [[RequestGinsengModel alloc] init];
    GetAllLastestVehicleDynamicModel.URL         = GetAllLastestVehicleDynamicURL;
    GetAllLastestVehicleDynamicModel.DataValue   = [self dataValue];
    GetAllLastestVehicleDynamicModel.UpdatedTime = [requestHelper getCurrentTime];
    GetAllLastestVehicleDynamicModel.SystemCode  = @"GuangleHighway";
    GetAllLastestVehicleDynamicModel.MethodName  = @"GetAlarmVehicleInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel) {
        //NSLog(@"%@",requestOutginseng.DataValue);
        _dataSource = [DetailModel mj_objectWithKeyValues:requestOutginseng.DataValue];
        [_tableView reloadData];
//        [];
    };
    [requestHelper RequestGinsengModel:GetAllLastestVehicleDynamicModel andPushController:self];
}


- (void)showCameraGunArround2KM {
    MACircle *circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake([_gaoModel.Latitude floatValue] ,[_gaoModel.Longitude floatValue]) radius:2000];
    [_mapView addOverlay: circle];
    
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray              = myDelegate.AllDeviceBaseArray ;
    NSMutableArray *tempDeviceArray       = [[NSMutableArray alloc] init];
    for (DeviceBaseInfo *model in dataSourceArray) {
        if (model.DeviceType == DevicesTypeCamera) {
            [tempDeviceArray addObject:model];
        }
    }
    NSMutableArray *containArray          = [[NSMutableArray alloc] init];
    for (DeviceBaseInfo *baseInfoModel in tempDeviceArray) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(baseInfoModel.Latitude, baseInfoModel.Longitude);
        BOOL isContain = MACircleContainsCoordinate(coordinate, CLLocationCoordinate2DMake([_gaoModel.Latitude floatValue], [_gaoModel.Longitude floatValue]), 2000);
        if (isContain) {
            [containArray addObject:baseInfoModel];
        }
    }

    if (containArray.count == 0) {
        _cameraBtn.hidden = YES;
        return;
    }

    NSMutableArray *numberArray = [[NSMutableArray alloc] init];
    MAMapPoint center = MAMapPointForCoordinate(CLLocationCoordinate2DMake([_gaoModel.Latitude floatValue], [_gaoModel.Longitude floatValue]));
    for (DeviceBaseInfo *model in containArray) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(model.Latitude, model.Longitude);
        MAMapPoint point                  = MAMapPointForCoordinate(coordinate);
        CLLocationDistance distance       = MAMetersBetweenMapPoints(point,center);
        NSNumber *number                  = [NSNumber numberWithDouble:distance];
        [numberArray addObject:number];
    }
    NSNumber *min                         = [numberArray valueForKeyPath:@"@min.doubleValue"];
    NSInteger index                       = [numberArray indexOfObject:min];
    _baseInfoModel         = containArray[index];
    
    if ([_baseInfoModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        [_cameraBtn setTitle:[NSString stringWithFormat:@"%@+%ld",_baseInfoModel.PileNo,(long)_baseInfoModel.PileDistance] forState:UIControlStateNormal];
    }else {
        NSString *LStr       = @"L";
        NSString *beginLKStr = [LStr stringByAppendingString:_baseInfoModel.PileNo];
//        _pileNOLabel.text    = [NSString stringWithFormat:@"%@+%@至%@+%@",beginLKStr,_ceModel.BeginPileDistance,endLKStr,_ceModel.EndPileDistance];
    [_cameraBtn setTitle:[NSString stringWithFormat:@"%@+%ld",beginLKStr,(long)_baseInfoModel.PileDistance] forState:UIControlStateNormal];
    }
}

//摄像枪点击
- (void) cameraGunClick {
    CameraDetailController *cameraVC = [[CameraDetailController alloc] init];
    cameraVC.deviceBaseInfo          = _baseInfoModel;
    AppDelegate *myDelegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    HighwayMergeRoadRecordModel *highModel = [[HighwayMergeRoadRecordModel alloc] init];
    for (HighwayMergeRoadRecordModel *model in myDelegate.HighWayRoadArray) {
        if ([model.RoadUID isEqualToString:_gaoModel.RoadUID]) {
            highModel = model;
        }
    }
    cameraVC.currentRoadModel        = highModel;
    cameraVC.roadType                = DirectionTypeUPAndDown;
    [self.navigationController pushViewController:cameraVC animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}
////*************公司
//NSArray *array = [_eventModel.Department componentsSeparatedByString:@"公司"];
//NSString *fisrtStr = array[0];
//NSString *secondStr = array[1];
//NSString *startStr = @"";
//for (int i = 0; i < fisrtStr.length; i++) {
//    startStr = [startStr stringByAppendingString:@"*"];
//}
//NSString *aStr = [startStr stringByAppendingString:@"公司"];
//NSString *bStr ;
//if (startStr.length > 0) {
//    bStr = [aStr stringByAppendingString:secondStr];
//}
//_departmentLabel.text = [NSString stringWithFormat:@"施  工  单  位 :%@",bStr];
//
//NSInteger headerlength = _eventModel.Header.length;
//
//// 林**
//if (headerlength > 3) {
//    NSString *headerLastStr = @"";
//    NSInteger lastLen = headerlength - 3;
//    for (int i = 0; i <= lastLen ; i ++) {
//        headerLastStr =  [headerLastStr stringByAppendingString:@"*"];
//    }
//    NSString *fisrtNameStr = [_eventModel.Header substringWithRange:NSMakeRange(0, 2)];
//    NSString *nameStr = [fisrtNameStr stringByAppendingString:headerLastStr];
//    _headerLabel.text   = [NSString stringWithFormat:@"现 场 负 责 人 :%@",nameStr];
//}else {
//    NSString *headerLastStr = @"";
//    NSInteger lastLen = headerlength - 1;
//    for (int i = 0; i <= lastLen ; i ++) {
//        headerLastStr =  [headerLastStr stringByAppendingString:@"*"];
//    }
//    NSString *fisrtNameStr = [_eventModel.Header substringWithRange:NSMakeRange(0, 1)];
//    NSString *nameStr = [fisrtNameStr stringByAppendingString:headerLastStr];
//    _headerLabel.text   = [NSString stringWithFormat:@"现 场 负 责 人 :%@",nameStr];
//}
////152**********
//NSString *phoneLastStr = @"";
//for (int i = 0; i < 8; i ++) {
//    phoneLastStr = [phoneLastStr stringByAppendingString:@"*"];
//}
//NSString *phoneFirstStr = [_eventModel.Telephone substringWithRange:NSMakeRange(0, 3)];
//NSString *telStr = [phoneFirstStr stringByAppendingString:phoneLastStr];
//_contacterNO.text  = [NSString stringWithFormat:@"联系电话:%@",telStr];

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
        case 0:
            if (_dataSource.vehicleNo) {
                cell.textLabel.text=[NSString stringWithFormat:@"车牌号码：%@",_dataSource.vehicleNo];
            }
            else
            {
                cell.textLabel.text=[NSString stringWithFormat:@"车牌号码：%@",_gaoModel.VehicleNo];
            }
            break;
        case 1:
            if (_dataSource.vehicleType) {
                cell.textLabel.text=[NSString stringWithFormat:@"车辆类型：%@",_dataSource.vehicleType];
            }
            else
            {
                cell.textLabel.text=[NSString stringWithFormat:@"车辆类型："];
            }
            break;
        case 2:
            if (_dataSource.ownerName ) {
                cell.textLabel.numberOfLines = 0;
                NSString *nameStr = _dataSource.ownerName;
                if ([nameStr containsString:@"公司"]) {
                    NSArray *array = [_dataSource.ownerName componentsSeparatedByString:@"公司"];
                    NSString *fisrtStr = array[0];
                    NSString *secondStr = array[1];
                    NSString *startStr = @"";
                    for (int i = 0; i < fisrtStr.length; i++) {
                        startStr = [startStr stringByAppendingString:@"*"];
                    }
                    NSString *aStr = [startStr stringByAppendingString:@"公司"];
                    //                NSString *bStr ;
                    if (startStr.length > 0) {
                        aStr = [aStr stringByAppendingString:secondStr];
                    }
                    cell.textLabel.text=[NSString stringWithFormat:@"所属公司：%@",aStr];
                }else {
                    NSString *startStr = @"";
                    for (int i = 0 ; i < nameStr.length; i ++) {
                         startStr = [startStr stringByAppendingString:@"*"];
                    }
                    NSString *aStr = [startStr stringByAppendingString:@"公司"];
                    cell.textLabel.text=[NSString stringWithFormat:@"所属公司：%@",aStr];
                }
            }
            else
            {
                cell.textLabel.text=[NSString stringWithFormat:@"所属公司："];
            }
            break;
        case 3:
            if (_dataSource.principalName.length > 0) {
//                cell.textLabel.text=[NSString stringWithFormat:@"联  系   人：%@",_dataSource.principalName];
                
                NSInteger headerlength = _dataSource.principalName.length;
                if (headerlength > 3) {
                    NSString *headerLastStr = @"";
                    NSInteger lastLen = headerlength - 3;
                    for (int i = 0; i <= lastLen ; i ++) {
                        headerLastStr =  [headerLastStr stringByAppendingString:@"*"];
                    }
                    NSString *fisrtNameStr = [_dataSource.principalName substringWithRange:NSMakeRange(0, 2)];
                    NSString *nameStr = [fisrtNameStr stringByAppendingString:headerLastStr];
                    cell.textLabel.text   = [NSString stringWithFormat:@"联  系   人：%@",nameStr];
                }else {
                    NSString *headerLastStr = @"";
                    NSInteger lastLen = headerlength - 1;
                    for (int i = 0; i < lastLen ; i ++) {
                        headerLastStr =  [headerLastStr stringByAppendingString:@"*"];
                    }
                    NSString *fisrtNameStr = [_dataSource.principalName substringWithRange:NSMakeRange(0, 1)];
                    NSString *nameStr = [fisrtNameStr stringByAppendingString:headerLastStr];
                   cell.textLabel.text   = [NSString stringWithFormat:@"联  系   人：%@",nameStr];
                }

            }
            else
            {
                cell.textLabel.text=[NSString stringWithFormat:@"联  系  人："];
            }
            break;
        case 4:
//            if (_dataSource.principalTelephone.length > 0) {
//                if (_dataSource.principalTelephone.length == 12) {
//                    //152**********
//                NSInteger length = _dataSource.principalTelephone.length;
//                    NSString *phoneLastStr = @"";
//                    for (int i = 0; i < length - 5; i ++) {
//                        phoneLastStr = [phoneLastStr stringByAppendingString:@"*"];
//                    }
//                    NSString *phoneFirstStr = [_dataSource.principalTelephone substringWithRange:NSMakeRange(0, 5)];
//                    NSString *telStr = [phoneFirstStr stringByAppendingString:phoneLastStr];
//                    cell.textLabel.text=[NSString stringWithFormat:@"联系电话：%@",telStr];
//                }
                if (_dataSource.principalTelephone.length > 0 ) { //
                    NSString *phoneLastStr = @"";
                    for (int i = 0; i < _dataSource.principalTelephone.length - 3; i ++) {
                        phoneLastStr = [phoneLastStr stringByAppendingString:@"*"];
                    }
                    NSString *phoneFirstStr = [_dataSource.principalTelephone substringWithRange:NSMakeRange(0, 3)];
                    NSString *telStr = [phoneFirstStr stringByAppendingString:phoneLastStr];
                    cell.textLabel.text=[NSString stringWithFormat:@"联系电话：%@",telStr];
                }
//            }
            else {
                cell.textLabel.text=[NSString stringWithFormat:@"联系电话："];
            }
            break;
        case 5:
            if (_dataSource.licenseCode.length > 0) {
                cell.textLabel.text=[NSString stringWithFormat:@"运输证号：%@",_dataSource.licenseCode];
            }
            else
            {
                cell.textLabel.text=[NSString stringWithFormat:@"运输证号："];
            }
            break;
        default:
            break;
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}


#pragma mark -地图代理方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CustomAnnotationView *annotationView   = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.selected              = NO;
        ROPointAnnotation *anno              = (ROPointAnnotation *)annotation;
        annotationView.vehicleModel          = anno.vehicleModel;
        annotationView.calloutView.backgroundColor = [UIColor clearColor];
        if (_type == AllIconTypeDangerous) {
            annotationView.image = [UIImage imageNamed:@"dynamic_vehilce"];//危化品车图标
        }else {
            annotationView.image = [UIImage imageNamed:@"commercial _vehicle"];// 客车图标
        }
        return annotationView;
    }
    return nil;
}
#pragma mark - 选中annotation时调用
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    CustomAnnotationView *customView     = (CustomAnnotationView *)view;
    customView.selected                  = NO;//让车辆图标不能被选中
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MACircle class]]){
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc]initWithCircle:overlay];
        circleRenderer.lineWidth   = 5.f;
        circleRenderer.fillColor   = [UIColor clearColor];
        circleRenderer.strokeColor = [UIColor clearColor];
        circleRenderer.lineWidth   = 5.f;
        circleRenderer.lineDash    = YES;
        
        return circleRenderer;
    }
    return nil;
}

-(NSString *)dataValue {
    NSMutableDictionary *dicKey=[[NSMutableDictionary alloc] init];
    [dicKey setObject:@"VehicleNo" forKey:@"key"];
    [dicKey setObject:_gaoModel.VehicleNo forKey:@"Value"];
    NSMutableArray *mutabl=[[NSMutableArray alloc] init];
    [mutabl addObject:dicKey];
    NSString *str=[mutabl mj_JSONString];
    return str;
}


@end
